/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package com.gitee.minimalismstyle.fresh.simple.service.impl

import com.gitee.minimalismstyle.fresh.common.core.domain.R
import com.gitee.minimalismstyle.fresh.common.core.extra.copyProperties
import com.gitee.minimalismstyle.fresh.common.data.beetl.service.impl.LongModelBaseServiceImpl
import com.gitee.minimalismstyle.fresh.simple.dao.SimpleFormDao
import com.gitee.minimalismstyle.fresh.simple.api.model.SimpleForm
import com.gitee.minimalismstyle.fresh.simple.api.model.SimpleFormFields
import com.gitee.minimalismstyle.fresh.simple.api.service.SimpleFormService
import com.gitee.minimalismstyle.fresh.simple.dao.SimpleFormFieldDao
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Primary
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * 表单业务实现
 * @author maoxiaodong
*/
@Primary
@Service
class SimpleFormServiceImpl: SimpleFormService, LongModelBaseServiceImpl<SimpleFormDao, SimpleForm>(){
    @Autowired
    private lateinit var simpleFormFieldDao: SimpleFormFieldDao

    @Transactional
    override fun saveSimpleFormFields(simpleFormFields: SimpleFormFields): R<SimpleFormFields> {
        if(simpleFormFields.id != null){
            simpleFormFieldDao.deleteByFormId(simpleFormFields.id!!)
        }
        val simpleForm = simpleFormFields.copyProperties(SimpleForm::class)
        dao.save(simpleForm)
        simpleForm.copyProperties(simpleFormFields)
        if(simpleFormFields.fields.isNotEmpty()){
            simpleFormFields.fields.forEach {
                it.reset()
                it.formId = simpleFormFields.id
            }
            simpleFormFieldDao.insertAll(simpleFormFields.fields)
        }
        return R.success(simpleFormFields)
    }

    override fun findSimpleFormFieldsById(id: Long): R<SimpleFormFields> {
        val simpleFormFields = SimpleFormFields()
        val simpleForm = dao.findById(id)
        BeanUtils.copyProperties(simpleForm, simpleFormFields)
        simpleFormFields.fields = simpleFormFieldDao.findByFormId(id)
        return R.success(simpleFormFields)
    }

}